<template>
  <div class="nav">
    <Nav/>
  </div>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="resetForm">注册</el-button>
          <el-button @click="change">修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, inject } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router.js'
import Nav from '@/views/Layout/nav.vue';
import store  from '@/vuex.js';
const axios = inject('$axios');

const loginForm = reactive({
  username: '',
  password: '',
});

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度至少为3位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
  ],
});

const loginFormRef = ref(null);

const handleLogin = async () => {
  if (!loginFormRef.value.validate()) {
    return;
  }
  // 这里可以添加实际的登录逻辑，比如发送axios请求到后端验证用户名和密码
  const res = await axios({
      method: 'post',
      url: '/login',
      data: {
          account: loginForm.username,
          password: loginForm.password,
      }
  });
  // 暂时模拟登录成功提示
  ElMessage.success('登录成功');
  const token = res.data.data;
  //将登录信息存入全局管理器
  store.commit('setUsername', loginForm.username);
  store.commit('setToken', token);
  console.log("全局变量已经写入登录用户信息："+loginForm.username);
  console.log("全局变量已经写入登录用户token："+token);
  router.push('/');
};

const resetForm = () => {
    router.push('/regist');
};
const change = () => {
    router.push('/change');
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.login-card {
  width: 360px;
  background-color: #ffffff;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}
</style>